package com.icesoft.core.web.suppose.mapping;

import com.icesoft.core.common.helper.AnnotationUtil;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ConditionMatchRequestMappingHandlerMapping extends RequestMappingHandlerMapping {

	@Override
	protected RequestCondition<ConditonMappingCondition> getCustomTypeCondition(Class<?> handlerType) {
		HeaderMappingGroup headerMappingGroup = handlerType.getAnnotation(HeaderMappingGroup.class);
		HeaderMapping headerMapping = handlerType.getAnnotation(HeaderMapping.class);
		VersionCodeMapping versionCode = handlerType.getAnnotation(VersionCodeMapping.class);
		return createCondition(headerMappingGroup, headerMapping, versionCode);
	}

	@Override
	protected RequestCondition<ConditonMappingCondition> getCustomMethodCondition(Method method) {
		HeaderMappingGroup headerMappingGroup = AnnotationUtil.findAnyAnnotation(method, HeaderMappingGroup.class);
		HeaderMapping headerMapping = AnnotationUtil.findAnyAnnotation(method, HeaderMapping.class);
		VersionCodeMapping versionCode = AnnotationUtil.findAnyAnnotation(method, VersionCodeMapping.class);
		return createCondition(headerMappingGroup, headerMapping, versionCode);
	}

	private RequestCondition<ConditonMappingCondition> createCondition(HeaderMappingGroup headerMappingGroup,
			HeaderMapping headerMapping, VersionCodeMapping versionCode) {
		if (headerMappingGroup == null && headerMapping == null && versionCode == null) {
			return null;
		}
		List<HeaderMapping> headerMappings = null;
		if (headerMapping != null || headerMappingGroup != null) {
			headerMappings = new ArrayList<>();
			if (headerMappingGroup != null) {
				headerMappings.addAll(Arrays.asList(headerMappingGroup.HeaderMapping()));
			}
			if (headerMapping != null) {
				headerMappings.add(headerMapping);
			}
		}
		return new ConditonMappingCondition(headerMappings, versionCode);
	}
}
